<template>
  <div class="tasks-page">
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">任务管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="$router.push('/tasks/create')">
            <el-icon><Plus /></el-icon>
            创建任务
          </el-button>
          <el-button @click="fetchTasks">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 搜索过滤 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchQuery"
              placeholder="搜索任务名称"
              @input="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="fetchTasks" clearable>
              <el-option label="全部" value="" />
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="fetchTasks">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 任务列表 -->
      <el-table
        :data="tasks"
        v-loading="loading"
        element-loading-text="加载中..."
        empty-text="暂无任务"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="任务名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="schedule_type" label="调度类型" width="120">
          <template #default="scope">
            <el-tag :type="getScheduleType(scope.row.schedule_type)">
              {{ getScheduleText(scope.row.schedule_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'danger'">
              {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_execution_status" label="最近执行" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.last_execution_status" :type="getStatusType(scope.row.last_execution_status)">
              {{ getStatusText(scope.row.last_execution_status) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="table-actions">
              <el-button size="small" @click="viewTask(scope.row.id)">详情</el-button>
              <el-button size="small" @click="editTask(scope.row.id)">编辑</el-button>
              <el-button
                size="small"
                type="success"
                @click="executeTask(scope.row.id)"
                :disabled="scope.row.status !== 'enabled'"
              >
                执行
              </el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="verify">验证配置</el-dropdown-item>
                    <el-dropdown-item command="toggle">
                      {{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { taskApi } from '../api'

const router = useRouter()

// 数据状态
const tasks = ref([])
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      search: searchQuery.value || undefined,
      status: statusFilter.value || undefined
    }

    const response = await taskApi.getTasks(params)
    tasks.value = response.data?.items || []
    pagination.total = response.data?.total || 0
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  fetchTasks()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchTasks()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchTasks()
}

// 查看任务详情
const viewTask = (id) => {
  router.push(`/tasks/${id}`)
}

// 编辑任务
const editTask = (id) => {
  router.push(`/tasks/${id}/edit`)
}

// 执行任务
const executeTask = async (id) => {
  try {
    await taskApi.executeTask(id)
    ElMessage.success('任务执行已提交')
    fetchTasks()
  } catch (error) {
    console.error('执行任务失败:', error)
  }
}

// 处理下拉菜单命令
const handleCommand = async (command, task) => {
  switch (command) {
    case 'verify':
      await verifyTask(task.id)
      break
    case 'toggle':
      await toggleTaskStatus(task)
      break
    case 'delete':
      await deleteTask(task)
      break
  }
}

// 验证任务配置
const verifyTask = async (id) => {
  try {
    const response = await taskApi.verifyTask(id)
    ElMessage.success('任务验证完成')
    console.log('验证结果:', response.data)
  } catch (error) {
    console.error('验证任务失败:', error)
  }
}

// 切换任务状态
const toggleTaskStatus = async (task) => {
  try {
    const newStatus = task.status === 'enabled' ? 'disabled' : 'enabled'
    await taskApi.updateTask(task.id, { status: newStatus })
    ElMessage.success(`任务已${newStatus === 'enabled' ? '启用' : '禁用'}`)
    fetchTasks()
  } catch (error) {
    console.error('切换任务状态失败:', error)
  }
}

// 删除任务
const deleteTask = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务"${task.name}"吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await taskApi.deleteTask(task.id)
    ElMessage.success('任务删除成功')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败')
    }
  }
}

// 获取调度类型样式
const getScheduleType = (type) => {
  const typeMap = {
    manual: 'info',
    scheduled: 'success',
    triggered: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取调度类型文本
const getScheduleText = (type) => {
  const textMap = {
    manual: '手动',
    scheduled: '定时',
    triggered: '触发'
  }
  return textMap[type] || type
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    success: 'success',
    running: 'warning',
    failed: 'danger',
    pending: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    success: '成功',
    running: '运行中',
    failed: '失败',
    pending: '等待中'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.tasks-page {
  padding: 0;
}

.filter-section {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>